/**
 * 
 */

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;

/**
 * @author Ashish Tomar
 *
 */
public class DownloadCableInfo extends HttpServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	//Generate the merged file header
	String mergedKmlString = "";

	String mergedPreamble = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
	"<kml xmlns=\"http://www.opengis.net/kml/2.2\">" +
	"<Document>" +
	"<name>Coned Data Browser</name>" +
	"<ScreenOverlay id=\"legend\">" +
	"<name>legend</name>" +
	"<Icon>" +
	"<href>legend.png</href>" +
	"</Icon>" +
	"<overlayXY x=\"0.5\" y=\"0\" xunits=\"fraction\" yunits=\"fraction\"/>" +
	"<screenXY x=\"0.2\" y=\"0.01\" xunits=\"fraction\" yunits=\"fraction\"/>" +
	"<rotationXY x=\"0\" y=\"0\" xunits=\"fraction\" yunits=\"fraction\"/>" +
	"<size x=\"0\" y=\"0\" xunits=\"fraction\" yunits=\"fraction\"/>" + 
	"</ScreenOverlay>" ;

	String mergedPost = "</Document>" +
	"</kml>";

	String linkMerge= "<NetworkLink><name>%1$s</name>" +
	"<visibility>1</visibility>" +            
	"<open>1</open>" +
	" <Link>" +
	"<href>"+"query%1$s.kml" +"</href>" +
	"</Link>" + 
	"</NetworkLink>\n" ;

	String preFolder="<Folder>"+
	"<name>%s</name>" +
	"<open>1</open>\n" ;
	//"<description>MHE</description>" ;

	String postFolder="</Folder>\n";

	//Begin creating the merged kml files
	ByteArrayOutputStream baosMerged = new ByteArrayOutputStream();
	PrintStream streamMerged = new PrintStream(baosMerged);

	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
	{
		//Obtain the type of trouble type as specified by user

		List<String> getBorough = new Vector<String>();



		String getBoroughTypeTmp[]= request.getParameterValues("boroughs");
		for (int i=0; i<getBoroughTypeTmp.length; i++){
			getBorough.add(getBoroughTypeTmp[i]);
		}






		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ZipOutputStream zipOut = new ZipOutputStream(baos);


		{
			response.setContentType("multipart/x-mixed-replace;boundary=randomstring");
			String fileHead = "--randomstring\n" +
			"Content-type:application/x-download\n" +
			"Content-Disposition:attachment;filename=cableQuery.zip\n\n";	
			//Change to getOutputStream
			OutputStream stream = response.getOutputStream();

			//FileOutputStream stream = new FileOutputStream(getServletContext().getRealPath("")+"/cablequery.zip");
			//FileOutputStream stream = new FileOutputStream(getServletContext().getRealPath("Downloads")+"/query.zip");
			String getKML = request.getParameter("getkml");
			//System.out.println(getKML);
			//Get the header information for the merged file.
			streamMerged.println(mergedPreamble);

			for (byte b : fileHead.getBytes())
			{
				stream.write(b);
			}

			{


				packageKML (getKML, "Cable", new RWPlacemark(), zipOut, getBorough);
				streamMerged.printf(linkMerge, "Cable");

				streamMerged.println(mergedPost);
				//Merge all the kml files created thus far
				mergedKmlString=baosMerged.toString();
				//				//Test to see if the merged network works ok.
				//				System.out.println("=======Printing the merged KML file here ======");
				//				System.out.println(mergedKmlString);

				//Add the merged file to the zip entry also
				ZipEntry mergeZip = new ZipEntry("merge.kml");
				zipOut.putNextEntry(mergeZip);
				for (byte b : mergedKmlString.getBytes())
				{
					zipOut.write(b);
				}

				//Add the legend PNG here
				try
				{
					File sourceFile=new File(getServletContext().getRealPath("WEB-INF") +"/legend.png");
					FileInputStream streamer = new FileInputStream(sourceFile);
					byte[] byteArray=new byte[streamer.available()];
					streamer.read(byteArray);
					streamer.close();

					ZipEntry zipPng = new ZipEntry("legend.png");
					zipOut.putNextEntry(zipPng);
					zipOut.write(byteArray);

				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				streamMerged.flush();
				streamMerged.close();
				zipOut.flush();
				zipOut.close();
				for (byte b: baos.toByteArray()) 
				{
					stream.write(b);
				}
			} // end of if getKML != null
			stream.flush();
			stream.close();

			//Print the response
			response.setContentType("text/html");
			//System.out.println("THE PATHS ARE-- ");
			//System.out.println(getServletContext().getRealPath("Downloads"));
			//System.out.println(getServletContext().getRealPath("."));
			//System.out.println(getServletContext().getRealPath(""));

			PrintWriter out = response.getWriter();
			out.println("<html>");
			out.println("<body>");
			out.println("<head>");

			out.println("<title>Done</title>");
			out.println("</head>");
			out.println("The downloading is completed. Please access the files from the following directory:");
			out.println("<br>");
			out.println("<br>");
			out.println("<h3> "+ getServletContext().getRealPath("") +"\\");
			//out.println("<h3> http://tecac-x2100f.ldeo.columbia.edu/strayVoltage/Downloads/");
			out.println("</body>");
			out.println("</html>");
		} // end of else loop 
	} 


	private void packageKML (String getKML, String troubleType, Placemark placemark, ZipOutputStream zipOut, List<String> getBorough) throws ServletException, IOException{
		GenerateKMLInfo generateKML = null;
		GenerateCableKMLInfo generateCableKML = null;
		try
		{
			if(!troubleType.equals("Cable"))
			{
				generateKML = new GenerateKMLInfo(getKML,troubleType, placemark, getBorough);

			}
			else if(troubleType.equals("Cable")){
				generateCableKML = new GenerateCableKMLInfo(getKML,troubleType, placemark, getBorough,1);
				// 1 here represents that ALL THE DATA FROM TABLE IS REQUIRED HERE
			}
		}
		catch (Exception e)
		{
			throw new ServletException(e.getMessage());
		}

		if(!troubleType.equals("Cable"))
		{
			String nameKMLFile = "query" + troubleType + ".kml";
			ZipEntry entry = new ZipEntry(nameKMLFile); // Make a ZipEntry
			zipOut.putNextEntry(entry); // Store entry
			for (byte b : generateKML.kmlString.getBytes())
			{
				zipOut.write(b);
			}
			MakePng makepng = new MakePng(placemark);
			makepng.addPngsToZip(zipOut);
		}
		else if(troubleType.equals("Cable")){
			String nameKMLFile = "query" + troubleType + ".kml";
			ZipEntry entry = new ZipEntry(nameKMLFile); // Make a ZipEntry
			zipOut.putNextEntry(entry); // Store entry
			for (byte b : generateCableKML.kmlString.getBytes())
			{
				zipOut.write(b);
			}

		}

	}

	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
	{
		doGet(request, response);
	}

	/**
	 * 
	 */
	public DownloadCableInfo() 
	{
		// TODO Auto-generated constructor stub
	}

}
